#include "log.h"
#include <ctime>
#include <cstdarg>
#include <clocale>

Log EngineLog;

Log::Log()
{
	_init("log.txt");
	set_time_record(true);
}

Log::Log(bool timerecord)
{
	_init("log.txt");
	set_time_record(timerecord);
}

Log::Log(char *name)
{
	_init(name);
}

Log::Log(char *name, bool timerecord)
{
	_init(name);
	set_time_record(timerecord);
}

Log::~Log()
{
	time_t datetime = time(0);
/*
	char timer[9];
	_strtime(timer);
	char date[9];
	_strdate(date);
	fprintf(_file, "\n---------------------------------------\n");
	fprintf(_file, "End Log: %s %s.", date, timer);
*/
	fprintf(_file, "\n---------------------------------------\n");
	fprintf(_file, "End Log: %s", ctime(&datetime));
	fclose(_file);
}

void Log::_init(const char *name)
{
	_name = name;
	set_time_record(false);
	setlocale(LC_ALL, "rus");

	if( (_file = fopen(_name,"w")) == NULL )
	{
		printf("Error creating file...\n");
		return;
	}
	else
	{
		time_t datetime = time(0);
		fprintf(_file, "Log create: %s\n", ctime(&datetime));
/*
		char timer[9];
		_strtime(timer);
		char date[9];
		_strdate(date);
		fprintf(_file, "Log create: %s %s.\n", date, timer);
*/
		fprintf(_file, "---------------------------------------\n\n");
	}
}

void Log::print(const char *message, ...)
{
	va_list args;
	va_start(args, message);
	char buffer[1024];
	vsprintf(buffer, message, args);
	_message_log("", buffer);
	va_end(args);
}

void Log::info(const char *message, ...)
{
	va_list args;
	va_start(args, message);
	char buffer[1024];
	vsprintf(buffer, message, args);
	_message_log("*INFO: ", buffer);
	va_end(args);
}

void Log::warning(const char *message, ...)
{
	va_list args;
	va_start(args, message);
	char buffer[1024];
	vsprintf(buffer, message, args);
	_message_log("*WARNING: ", buffer);
	va_end(args);
}

void Log::error(const char *message, ...)
{
	va_list args;
	va_start(args, message);
	char buffer[1024];
	vsprintf(buffer, message, args);
	_message_log("*ERROR: ", buffer);
	va_end(args);
}

void Log::_message_log(const char *levtext, const char *text)
{
	if (_trec == true)
	{
		time_t datetime = time(0);
		//fprintf(_file, "Log create: %s.\n", ctime(&datetime));
/*
		char timer[9];
		_strtime(timer);
*/
		clock_t cl = clock();
/*
		printf("%s::%d: ", timer, cl); 
		fprintf(_file, "%s::%d: ", timer, cl);
*/
		char *ct = ctime(&datetime);
		printf("%s::%d: ", ct, cl); 
		fprintf(_file, "%s::%d: ", ct, cl);
	}
	printf("%s%s\n", levtext, text); 
	fprintf(_file, "%s%s\n", levtext, text);
	fflush(_file);
}